#!/usr/bin/python

import random

import gtk
import gtk.glade
import data
from neural_network import NN
from gtkcairoplot import gtk_function_plot


class UI:
		def __init__(self) :
				self.builder = gtk.Builder()
				self.builder.add_from_file("neuron_ui.xml")
				self.graph = gtk_function_plot()
				mainWindow = self.builder.get_object("mainWindow")
#				mainWindow.maximize()
				mainBox = self.builder.get_object("vbox3")
				mainBox.pack_start(self.graph)
				mainWindow.connect("delete-event", gtk.main_quit)
				
				self.epochSpin = self.builder.get_object("epochSpin")
				self.hiddenSpin = self.builder.get_object("hiddenSpin")
				self.eitaSpin = self.builder.get_object("eitaSpin")
				self.alphaSpin = self.builder.get_object("alphaSpin")
				self.sigmSpin = self.builder.get_object("sigmSpin")
				self.lambdaSpin = self.builder.get_object("lambdaSpin")
				self.testingCheck = self.builder.get_object("testingCheck")
				self.runNetwork = self.builder.get_object("runNetwork")
				self.plot = self.builder.get_object("plot")
				self.quit = self.builder.get_object("quit")
				
				self.runNetwork.connect("clicked", self.run_cb)
				self.plot.connect("clicked", self.plot_cb)
				
				self.network = NN()
				self.tmpList = []
			
				mainWindow.show_all()
				gtk.main()
				
		def plotFunction(self, num):
				if num > (len(self.tmpList) - 1):
						if len(self.tmpList) is 0 :
								return 0
						else :
								return self.tmpList[-1]
				else:	
						return self.tmpList[num]
		
		def run_cb(self, widget) :
				data.inputs_vec = []
				data.outputs_vec = []
				
				if self.testingCheck.get_active() :
						data.train = False
						input_file = open("testing.csv").readlines()
				else :
						data.train = True
						input_file = open("training.csv").readlines()
						self.network = None
						self.network = NN()
				
				for index, line in enumerate(input_file) :
						data.inputs_vec.append(((float(line.split(',')[0])) + 180.0) / 360.0)
						data.outputs_vec.append(((float(line.split(',')[1])) + 50.0) / 150.0)
				
				data.eita = float(self.eitaSpin.get_value())
				data.alpha = float(self.alphaSpin.get_value())
				data.lambda_coef = float(self.lambdaSpin.get_value())
				data.sig_coef = float(self.sigmSpin.get_value())
				data.epochs = self.epochSpin.get_value_as_int()
				data.hidden_neurons = self.hiddenSpin.get_value_as_int()		
				
				print data.epochs
				self.network.open_file(data.train)
				self.network.execute()
		
		def plot_cb(self, widget) :		
				print "Plotting graph..."
				i = 0
				self.tmpList = []
				while i < len(self.network.epoch_errors):
						self.tmpList.append(self.network.epoch_errors[i])
						i += 1
				self.graph.set_args({"data":self.plotFunction, "grid":True, "x_bounds":(0, data.epochs), "step":1, 
										"x_title":"Epochs", "y_title":"Average Error",  "series_colors":["red"]});							

app = UI()

